package com.woniu.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.util.ResponseResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {


            String headerToken = request.getHeader("strToken");
            System.out.println("logout header Token = " + headerToken);

            if (!StringUtils.isEmpty(headerToken)) {
                //清空上下文
                SecurityContextHolder.clearContext();
            }
        try {
            ResponseResult<String> result = new ResponseResult<>("","注销成功",200);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}
